package com.jstyle.jclife.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.jstyle.blesdk.cmdenum.SendCmdState;
import com.jstyle.jclife.BuildConfig;
import com.jstyle.jclife.NetWork.NetWorkException;
import com.jstyle.jclife.NetWork.NetWorkUtil;
import com.jstyle.jclife.R;

import com.jstyle.jclife.activity.AboutUsActivity;
import com.jstyle.jclife.activity.BPCalibrationActivity;
import com.jstyle.jclife.activity.BindDeviceListActivity;
import com.jstyle.jclife.activity.AutoHeartActivity;
import com.jstyle.jclife.activity.BaseActivity;
import com.jstyle.jclife.activity.BindDeviceActivity;
import com.jstyle.jclife.activity.DeviceSettingActivity;
import com.jstyle.jclife.activity.FeedBackActivity;
import com.jstyle.jclife.activity.FileUpdateActivity;
import com.jstyle.jclife.activity.GetSupportActivity;
import com.jstyle.jclife.activity.GoalActivity;
import com.jstyle.jclife.activity.LoginActivity;
import com.jstyle.jclife.activity.LoginOrSingInActivity;
import com.jstyle.jclife.activity.ThirdDataActivity;
import com.jstyle.jclife.activity.UserInfoActivity;
import com.jstyle.jclife.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclife.adapter.SettingAdapter;
import com.jstyle.jclife.app.MyApplication;
import com.jstyle.jclife.ble.BleManager;
import com.jstyle.jclife.daoManager.BindDeviceInfoDaoManager;
import com.jstyle.jclife.daoManager.GpsDataDaoManager;
import com.jstyle.jclife.daoManager.HealthDataDaoManager;
import com.jstyle.jclife.daoManager.HeartDataDaoManager;
import com.jstyle.jclife.daoManager.PathRecordDaoManager;
import com.jstyle.jclife.daoManager.SleepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclife.model.BindDeviceInfo;
import com.jstyle.jclife.model.UpdateData;
import com.jstyle.jclife.utils.DfuUtil;
import com.jstyle.jclife.utils.GlobalConast;
import com.jstyle.jclife.utils.ImageUtils;
import com.jstyle.jclife.utils.NetWorkConast;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.SharedPreferenceUtils;
import com.jstyle.jclife.utils.ZipUtils;
import com.jstyle.jclife.view.TipsDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SettingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingFragment extends BaseFragment implements RecyclerViewBaseAdapter.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.RecyclerView)
    RecyclerView RecyclerView_setting;
    Unbinder unbinder;
    @BindArray(R.array.array_setting)
    String[] arraySetting;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private SettingAdapter settingAdapter;
    private String updateFilePath;
    private boolean isNeedUpdate;
    private String otaPath;
    private String deviceVersion;

    public SettingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingFragment newInstance(String param1, String param2) {
        SettingFragment fragment = new SettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        //  sendData(SendCmdState.READ_DEVICE_BATTERY);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        settingAdapter = new SettingAdapter(Arrays.asList(arraySetting));
        settingAdapter.setOnItemClickListener(this);
        RecyclerView_setting.setAdapter(settingAdapter);
        RecyclerView_setting.setLayoutManager(linearLayoutManager);
        if(mListener!=null)mListener.readBatteryAndVersion();
    }

    // TODO: Rename method, update argument and hook method into UI event

    @Override
    public void onResume() {
        super.onResume();
        settingAdapter.notifyDataSetChanged();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(int position) {
        switch (position) {
            case 1:
                String address = SharedPreferenceUtils.getSpString(SharedPreferenceUtils.KEY_ADDRESS);
                List<BindDeviceInfo> bindDeviceInfoList = BindDeviceInfoDaoManager.queryAllData();
                startActivity(bindDeviceInfoList.size() == 0 ? BindDeviceActivity.class : BindDeviceListActivity.class);
                break;
            case 3:
                startActivity(UserInfoActivity.class);
                break;
            case 4:
                startActivity(GoalActivity.class);
                break;
            case 5:
                startActivity(AutoHeartActivity.class);
                break;
            case 6:
                startActivity(BPCalibrationActivity.class);
                break;
            case 7:
                startActivity(DeviceSettingActivity.class);
                break;
            case 8:
                checkVersion();
                break;
//            case 7:
//                startActivity(DeviceSettingActivity.class,DeviceSettingActivity.Enable_Type,DeviceSettingActivity.KEY_Unit);
//                break;
            case 9:
                showResetDialog();
                break;
            case 11:
                startActivity(AboutUsActivity.class);
                break;
            case 12:
                startActivity(FeedBackActivity.class);
                break;
            case 13:
                exitLogin();
                break;
        }
    }

    private void exitLogin() {
        getActivity().finish();
        SharedPreferenceUtils.setSpBoolean(SharedPreferenceUtils.KEY_LOGIN, false);
        startActivity(LoginActivity.class);
    }

    private void checkVersion() {
        // showChargeDialog();

        if (BleManager.getInstance().isConnected()) {
            if (isNeedUpdate) {
                int battery = settingAdapter.getBattery();
                if (battery > 20) {
                    showUpdateDialog(updateFilePath,battery);
                } else {
                    showChargeDialog();
                }

            } else {
                showToast(getString(R.string.Latest_Version_Already));
            }
        } else {
            showToast(getString(R.string.Bluetooth_Disconnected));
        }

    }

    AlertDialog alertDialogCharge;

    private void showChargeDialog() {
        TipsDialog tipsDialog = new TipsDialog(getActivity(), R.style.jstyleDialog_style);
        tipsDialog.setContent(getString(R.string.Low_battery_caution_content));
        tipsDialog.setConfimText(getString(R.string.low_battery_ok));
        tipsDialog.setButtonCancelGone();
        tipsDialog.show();
//        if(alertDialogCharge==null){
//            alertDialogCharge=new AlertDialog.Builder(getActivity())
//                    .setTitle(getString(R.string.Low_battery_caution))
//                    .setMessage()
//                    .setPositiveButton(,null).create();
//        }
//        if(!alertDialogCharge.isShowing())alertDialogCharge.show();
    }

    private void showUpdateDialog(final String filePath,int batteryValue) {
        Intent intent = new Intent(getActivity(), FileUpdateActivity.class);
        intent.putExtra(FileUpdateActivity.key_url, filePath);
        intent.putExtra(FileUpdateActivity.key_version, deviceVersion);
        intent.putExtra(FileUpdateActivity.key_battery, batteryValue);
        startActivity(intent);
    }



    private String updateFileName = "firmware.zip";







    private void showResetDialog() {
        if (!BleManager.getInstance().isConnected()) {
            showToast(getString(R.string.Bluetooth_Disconnected));
            return;
        }
        TipsDialog tipsDialog = new TipsDialog(getActivity(), R.style.jstyleDialog_style);
        tipsDialog.setTipsConfimListener(new TipsDialog.TipsConfimListener() {
            @Override
            public void onConfim() {
                sendData(SendCmdState.SET_FACTORY);
            }
        });
        tipsDialog.show();

    }

    private void deleteAllData() {
        GpsDataDaoManager.deleteAll();
        HeartDataDaoManager.deleteAll();
        HealthDataDaoManager.deleteAll();
        PathRecordDaoManager.deleteAll();
        SleepDataDaoManager.deleteAll();
        StepDetailDataDaoManager.deleteAll();
        StepDataDaoManager.deleteAll();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void readBatteryAndVersion();
    }

    private static final String TAG = "SettingFragment";

    public void updateBattery(String battery) {
        if (isAdded())
            settingAdapter.setBattery(battery);
        Log.i(TAG, "updateBattery: " + battery);
    }

    public void updateVersion(String updateFilePath, String version) {
        String versionCode = version.replace(".", "");
        this.updateFilePath = updateFilePath;
        deviceVersion = version;
//        settingAdapter.setBattery(battery);
//        Log.i(TAG, "updateBattery: "+battery);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
          if(mListener!=null)mListener.readBatteryAndVersion();
        }
    }


    public void changeUpdateStatus(boolean isNeedUpdate) {
        this.isNeedUpdate = isNeedUpdate;
        settingAdapter.setNeedUpdate(isNeedUpdate);
    }
}
